//
//  BigCardContentView.swift
//  大卡位 - 内容
//
//  Created by 千策万划-mini on 2025/4/30.
//

import Foundation

class BigCardContentView: UIView, UIScrollViewDelegate {

    var blockFeedbackSuccess: (() -> Void)?
    var blockApplyNow:(() -> Void)?
    var blockNoLogin:(() -> Void)?
    
    // MARK: - lazy
    lazy var imageTitle: UIImageView = {
        let result = UIImageView()
        result.widthHeight = XY(W(123), W(26))
        result.image = UIImage(named: "icon_home_title_logo")
        return result
    }()

    lazy var imageHouse: UIButton = {
        let result = UIButton()
        result.isUserInteractionEnabled = true
        result.widthHeight = XY(SCREEN_WIDTH, SCREEN_WIDTH / 375 * 425)
        result.setBackgroundImage(UIImage(named: "icon_home_big_top_bg"), for: .normal)
        result.tag = 2
        result.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
        return result
    }()

    lazy var labelDaysTitle: UILabel = {
        let result = UILabel()
        result.font = UIFont.customBoldFont(size: 14)
        result.textColor = UIColor(hex: "#5F2F0D")
        return result
    }()

    lazy var imageDayBg: UIImageView = {
        let result = UIImageView()
        result.widthHeight = XY(W(86), W(86))
        result.image = UIImage(named: "icon_home_day_bg")
        return result
    }()

    lazy var labelRateDay: OutlineLabel = {
        let result = OutlineLabel()
        return result
    }()

    lazy var labelDay: OutlineLabel = {
        let result = OutlineLabel()
        return result
    }()

    lazy var imageAmountTitle: OutlineLabel = {
        let result = OutlineLabel()
        return result
    }()

    lazy var labelAmount: OutlineLabel = {
        let result = OutlineLabel()
        return result
    }()

    lazy var imageGold: UIImageView = {
        let result = UIImageView()
        result.widthHeight = XY(38, 38)
        result.image = UIImage(named: "icon_home_big_gold")
        return result
    }()

    lazy var btnApply: UIButton = {
        let result = UIButton()
        result.widthHeight = XY(W(180), W(71))
        result.setImage(UIImage(named: "icon_home_big_apply_now"), for: .normal)
        result.tag = 1
        result.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside)
        return result
    }()

    lazy var imageCompare: UIImageView = {
        let result = UIImageView()
        result.widthHeight = XY(SCREEN_WIDTH, SCREEN_WIDTH / 375 * 264)
        result.image = UIImage(named: "icon_home_big_compare")
        return result
    }()

    lazy var imageFeedback: UIImageView = {
        let result = UIImageView()
        result.isUserInteractionEnabled = true
        result.widthHeight = XY(SCREEN_WIDTH, SCREEN_WIDTH / 375 * 163)
        result.image = UIImage(named: "icon_home_big_feedback")
        let list: [ModelBtn] = [
            ModelBtn(imageName: "icon_home_feedback_1_uncheck", highImageName: "icon_home_feedback_1_check", title: "Not", content: "satisfied"),
            ModelBtn(imageName: "icon_home_feedback_2_uncheck", highImageName: "icon_home_feedback_2_check", title: "Generally", content: "satisfied"),
            ModelBtn(imageName: "icon_home_feedback_3_uncheck", highImageName: "icon_home_feedback_3_check", title: "Quite", content: "satisfied"),
            ModelBtn(imageName: "icon_home_feedback_4_uncheck", highImageName: "icon_home_feedback_4_check", title: "Very", content: "satisfied"),
        ]
        let left = W(20)
        for i in 0 ..< list.count {
            let model = list[i]
            let btnBack = UIButton()
            btnBack.widthHeight = XY((result.width - left * 2) / 4, result.height - W(64))

            let btnImage = UIButton()
            btnImage.isUserInteractionEnabled = false
            btnImage.setImage(UIImage(named: UnPackStr(model.imageName)), for: .normal)
            btnImage.setImage(UIImage(named: UnPackStr(model.highImageName)), for: .selected)
            btnImage.widthHeight = XY(W(42), W(42))
            btnImage.centerXTop = XY(btnBack.width / 2, W(16))
            btnBack.addSubview(btnImage)

            let label = UILabel()
            label.textColor = UIColor(hex: "#4E23D5")
            label.font = UIFont.customRegularFont(size: 12)
            label.fitTitle(UnPackStr(model.title), variable: 0)
            label.centerXTop = XY(btnImage.centerX, btnImage.bottom + W(2))
            btnBack.addSubview(label)

            let labelContent = UILabel()
            labelContent.textColor = UIColor(hex: "#4E23D5")
            labelContent.font = UIFont.customRegularFont(size: 12)
            labelContent.fitTitle(UnPackStr(model.content), variable: 0)
            labelContent.centerXTop = XY(btnImage.centerX, label.bottom - 5)
            btnBack.addSubview(labelContent)

            btnBack.tag = i
            btnBack.addTarget(self, action: #selector(btnFeedBackClick(_:)), for: .touchUpInside)

            btnBack.leftTop = XY(left + btnBack.width * CGFloat(i), W(46))
            // btnBack.backgroundColor = i == 0 ? .red : i == 1 ? .orange : i == 2 ? .yellow : .systemPink
            result.addSubview(btnBack)
        }
        return result
    }()

    lazy var imageAgree: UIImageView = {
        let result = UIImageView()
        result.widthHeight = XY(SCREEN_WIDTH, SCREEN_WIDTH / 375 * 88)
        result.image = UIImage(named: "icon_home_big_agree")
        result.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapAgreeClick(_:)))
        result.addGestureRecognizer(tap)
        return result
    }()

    lazy var imageVoices: UIImageView = {
        let result = UIImageView()
        result.isUserInteractionEnabled = true
        result.widthHeight = XY(SCREEN_WIDTH, SCREEN_WIDTH / 375 * 196)
        result.image = UIImage(named: "icon_home_big_voices")
        let scrollView = UIScrollView()
        scrollView.height = W(106)
        scrollView.backgroundColor = .clear
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.width = SCREEN_WIDTH - W(19) - W(19)
        scrollView.leftTop = XY(W(19), W(56))
        scrollView.delegate = self
        let list: [String] = ["icon_home_voices_1", "icon_home_voices_2", "icon_home_voices_3", "icon_home_voices_4"]
        for i in 0 ..< list.count {
            let image = UIImageView()
            image.widthHeight = XY(W(216), W(106))
            image.image = UIImage(named: list[i])
            image.leftTop = XY(W(15) + (image.width + W(10)) * CGFloat(i), 0)
            scrollView.addSubview(image)
        }
        scrollView.contentSize = CGSize(width: W(216 + 10) * CGFloat(list.count) + W(15 + 5), height: 0)
        result.addSubview(scrollView)
        return result
    }()

    lazy var labelNumer: UILabel = {
        let result = UILabel()
        result.font = UIFont.customSemiBoldFont(size: 14)
        result.textColor = UIColor(hex: "#4E23D5")
        result.fitTitle("1/4", variable: 0)
        return result
    }()

    // MARK: - init
    override init(frame: CGRect) {
        super.init(frame: frame)
        widthHeight = XY(SCREEN_WIDTH, 0)
        backgroundColor = .clear
        isUserInteractionEnabled = true

        addSubView()
    }

    @available(*, unavailable)
    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - 添加
    func addSubView() {
        addSubview(imageTitle)
        addSubview(imageHouse)

        imageHouse.addSubview(labelDaysTitle)
        imageHouse.addSubview(imageAmountTitle)
        imageHouse.addSubview(imageGold)
        imageHouse.addSubview(labelAmount)
        imageHouse.addSubview(btnApply)
        imageHouse.addSubview(imageDayBg)
        imageDayBg.addSubview(labelRateDay)
        imageDayBg.addSubview(labelDay)

        addSubview(imageCompare)
        addSubview(imageFeedback)
        addSubview(imageAgree)
        addSubview(imageVoices)
        imageVoices.addSubview(labelNumer)

        resetView()
    }

    // MARK: - 点击事件
    @objc func tapAgreeClick(_ tap: UITapGestureRecognizer) {
        feedback()
        tap.view?.addClickAnimate()
        if !isStr(GlobalData.sharedInstance.GB_SessionID) {
            if let block = blockNoLogin {
                block()
            }
        }else{
            let vc = BaseWebVC()
            vc.webUrl = LOCAL_LOAN_AGREEMEENT
            GB_Nav?.pushViewController(vc, animated: true)
        }
    }

    @objc func btnClick(_ sender: UIControl) {
        feedback()
        if sender.tag == 1 {
            sender.addClickAnimate()
        }
        if !isStr(GlobalData.sharedInstance.GB_SessionID) {
            if let block = blockNoLogin {
                block()
            }
        }else{
            switch sender.tag {
            case 1, 2:
                if let block = blockApplyNow {
                    block()
                }
                break
            default:
                break
            }
        }
    }

    @objc func btnFeedBackClick(_ sender: UIControl) {
        feedback()
        sender.addClickAnimate()
        if !isStr(GlobalData.sharedInstance.GB_SessionID) {
            if let block = blockNoLogin {
                block()
            }
        }else{
            setAllButtonsUnselected(in: imageFeedback)
            for subview in sender.subviews {
                if let button = subview as? UIButton {
                    button.isSelected = true
                }
            }
            GlobalMethod.writeBool(true, forKey: LOCAL_HOME_FEEDBACK, isPrefixed: false)
            GlobalMethod.showLoadingView()
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                GlobalMethod.hideLoadingView()
                GlobalMethod.showAlert(strAlert: "Thank you for your review")
                if let block = self.blockFeedbackSuccess {
                    block()
                }
            }
        }
    }

    func setAllButtonsUnselected(in view: UIView) {
        for subview in view.subviews {
            if let button = subview as? UIButton {
                button.isSelected = false
            }
            // 递归
            setAllButtonsUnselected(in: subview)
        }
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let itemWidth = W(216) + W(10)
        let page = Int((scrollView.contentOffset.x + itemWidth / 2) / itemWidth)
        let total = 4
        labelNumer.fitTitle("\(page + 1)/\(total)", variable: 0)
        labelNumer.rightCenterY = labelNumer.rightCenterY
    }

    // MARK: - 重置界面
    func resetView(_ model: ModelHome = ModelHome()) {
        let modelImpulsive: ModelHomeServesImpulsive = model.serves?.impulsive.first ?? ModelHomeServesImpulsive()

        imageTitle.centerXTop = XY(SCREEN_WIDTH / 2, W(12))
        imageHouse.centerXTop = XY(SCREEN_WIDTH / 2, -W(15))

        labelDaysTitle.fitTitle("\(UnPackStr(modelImpulsive.waved))：\(modelImpulsive.peeping)", variable: 0)
        labelDaysTitle.centerXTop = XY(imageHouse.width / 2, W(97))

        imageAmountTitle.resetView(
            title: UnPackStr(modelImpulsive.bold),
            textColor: UIColor(hex: "#F95882"),
            font: UIFont.customBoldFont(size: 22),
            shadowColor: UIColor(hex: "#FFFFFF"),
            outlineColor: UIColor(hex: "#FFFFFF")
        )
        imageAmountTitle.centerXTop = XY(imageHouse.width / 2, labelDaysTitle.bottom + W(80))

        labelAmount.resetView(
            title: UnPackStr(modelImpulsive.freedom),
            textColor: COLOR_WHITE(),
            font: UIFont.customBoldFont(size: 48),
            shadowColor: UIColor(hex: "#5F2F0D"),
            outlineColor: UIColor(hex: "#5F2F0D")
        )
        let leftMargin = (imageHouse.width - imageGold.width - labelAmount.width) / 2
        imageGold.leftTop = XY(leftMargin, imageAmountTitle.bottom + W(12))
        labelAmount.leftCenterY = XY(imageGold.right, imageGold.centerY)

        btnApply.centerXBottom = XY(imageHouse.width / 2, imageHouse.height)
        imageDayBg.rightBottom = XY(SCREEN_WIDTH - 10, imageHouse.height - W(64))

        // 利率 - 日
        let nervous = UnPackStr(modelImpulsive.nervous)
        let nervousParts = nervous.components(separatedBy: "/")
        let rate = nervousParts.first ?? ""
        let unit = (nervousParts.count > 1 ? nervousParts[1] : "").uppercased() // 大写

        labelRateDay.removeAllSubviews()
        labelDay.removeAllSubviews()
        labelRateDay.isHidden = true
        labelDay.isHidden = true
        if isStr(rate) {
            labelRateDay.resetView(
                title: rate,
                textColor: COLOR_WHITE(),
                font: UIFont.customExtraBoldFont(size: 18),
                shadowColor: UIColor(hex: "#5F2F0D"),
                outlineColor: UIColor(hex: "#5F2F0D")
            )
            labelDay.resetView(
                title: unit,
                textColor: COLOR_WHITE(),
                font: UIFont.customExtraBoldFont(size: 18),
                shadowColor: UIColor(hex: "#5F2F0D"),
                outlineColor: UIColor(hex: "#5F2F0D")
            )
        }
        let transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 8)
        labelRateDay.centerXCenterY = XY(imageDayBg.width / 2 - W(9), imageDayBg.height / 2 - W(7))
        labelRateDay.transform = transform
        labelDay.centerXTop = XY(labelRateDay.centerX + W(8), labelRateDay.bottom - W(24))
        labelDay.transform = transform
        labelRateDay.isHidden = false
        labelDay.isHidden = false

        imageCompare.centerXTop = XY(SCREEN_WIDTH / 2, imageHouse.bottom)

        imageFeedback.isHidden = GlobalMethod.readBoolFromUserDefaults(forKey: LOCAL_HOME_FEEDBACK, isPrefixed: false)
        imageFeedback.centerXTop = XY(SCREEN_WIDTH / 2, imageCompare.bottom)

        imageAgree.centerXTop = XY(SCREEN_WIDTH / 2, imageFeedback.isHidden == false ? imageFeedback.bottom : imageCompare.bottom)
        imageVoices.centerXTop = XY(SCREEN_WIDTH / 2, imageAgree.bottom)
        labelNumer.rightTop = XY(SCREEN_WIDTH - W(34), W(16))

        height = imageVoices.bottom + LEFT_MARGIN * 2
    }
}
